class TodoTemplate {
  todoView({ id, content, completed }) {
    return `
    <input type='checkbox'   ${completed ? "checked" : ""}   data-id='${id}' />
    <span style='text-decoration: ${
      completed ? "line-through" : ""
    }  '   >${content}</span>
    <button data-id='${id}' >删除</button>
    `;
  }
}

function findParentNode(target, name) {
  while ((target = target.parentNode)) {
    if (target.className.trim() === name) {
      return target;
    }
  }
}

function createItem(tagName, className, content) {
  const oItem = document.createElement(tagName);
  oItem.className = className;
  oItem.innerHTML = content;
  return oItem;
}
class TodoDom extends TodoTemplate {
  constructor(todoWrapper) {
    super();
    this.todoWrapper = todoWrapper;
  }

  initList(dataList) {
    const oFrag = document.createDocumentFragment();
    let oItem = null;
    dataList.forEach((v) => {
      oItem = createItem("div", "todo-item", this.todoView(v));
      oFrag.appendChild(oItem);
    });
    this.todoWrapper.appendChild(oFrag);
  }
  addItem(todo) {
    const oItem = createItem("div", "todo-item", this.todoView(todo));
    this.todoWrapper.appendChild(oItem);
  }
  removeItem(target) {
    const parentNode = findParentNode(target, "todo-item");
    parentNode.remove();
  }
  changeCompleted(target, completed) {
    const parentNode = findParentNode(target, "todo-item");
    const span = parentNode.getElementsByTagName("span")[0];
    span.style.textDecoration = completed ? "line-through" : "none";
  }
}

class TodoEvent extends TodoDom {
  constructor(todoData, todoWrapper) {
    super(todoWrapper);
    this.todoData = todoData;
    this.el = todoWrapper;
    this.initList(this.todoData);
  }
  addTodo(todo) {
    const item = this.todoData.find((v) => v.content === todo.content);
    if (item) {
      return 1001;
    }
    this.todoData.push(todo);
    this.addItem(todo);
  }
  removeTodo(target, id) {
    this.todoData = this.todoData.filter((v) => {
      v.id !== id;
    });
    this.removeItem(target, id);
  }
  toggleComplete(target, id) {
    this.todoData = this.todoData.map((v) => {
      if (v.id === id) {
        v.completed = !v.completed;
        console.log(target, v.completed);
        this.changeCompleted(target, v.completed);
      }
      return v;
    });
  }
}
